package com.analysis.controller;

import com.analysis.dto.*;
import com.analysis.entity.Project;
import com.analysis.entity.ProjectBrand;
import com.analysis.entity.References;
import com.analysis.enums.RequireLogin;
import com.analysis.entity.User;
import com.analysis.service.ProjectBrandService;
import com.analysis.service.ProjectService;
import com.analysis.service.UserService;
import com.analysis.service.QuestionService;
import com.analysis.utils.PasswordMigrationUtil;
import com.analysis.utils.RedisSessionManager;
import com.analysis.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisSessionManager sessionManager;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectBrandService projectBrandService;
    @Autowired
    private PasswordMigrationUtil passwordMigrationUtil;
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 参数验证
            if (loginRequest.getNick() == null || loginRequest.getNick().trim().isEmpty()) {
                return ApiResponse.error("用户名不能为空");
            }
            if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
                return ApiResponse.error("密码不能为空");
            }
            
            // 验证用户登录
            User user = userService.login(loginRequest.getNick(), loginRequest.getPassword());
            if (user != null) {
                // 创建会话
                String token = sessionManager.createSession(user);
                LoginResponse loginResponse = LoginResponse.success(token, user);
                return ApiResponse.success(loginResponse);
            } else {
                return ApiResponse.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return ApiResponse.error("登录时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @RequireLogin
    public ApiResponse<String> logout(HttpServletRequest request) {
        try {
            String token = (String) request.getAttribute("userToken");
            if (token != null) {
                sessionManager.removeSession(token);
            }
            return ApiResponse.success("登出成功");
        } catch (Exception e) {
            return ApiResponse.error("登出时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    @RequireLogin
    public ApiResponse<User> getCurrentUser(HttpServletRequest request) {
        try {
            User currentUser = UserUtils.getCurrentUser(request);
            if (currentUser != null) {
                // 创建安全副本，不返回密码信息
                User safeUser = UserUtils.createSafeUserCopy(currentUser);
                return ApiResponse.success(safeUser);
            } else {
                return ApiResponse.error("用户信息不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息时发生错误: " + e.getMessage());
        }
    }


    /**
     * 查询所有的品牌
     */
    @GetMapping("/brandList")
    @RequireLogin
    public ApiResponse<List<String>> brandList(HttpServletRequest request) {
        try {
            // 获取当前用户ID
            User user = UserUtils.getCurrentUser(request);
            if (user == null) {
                return ApiResponse.error("用户未登录或会话已过期");
            }
            List<Project> projects =  projectService.listByCompany(user.getCompanyId());
            List<ProjectBrand> brands = projectBrandService.listByProjectIds(projects.stream().map(Project::getId).collect(Collectors.toList()));
            return ApiResponse.success(brands.stream().map(ProjectBrand::getProductName).collect(Collectors.toList()));
        } catch (Exception e) {
            return ApiResponse.error("查询用户品牌列表失败: " + e.getMessage());
        }
    }


    /**
     * 迁移所有用户密码（谨慎使用）
     */
    @PostMapping("/migrate-all")
    public ApiResponse<String> migrateAllPasswords() {
        try {
            passwordMigrationUtil.migrateAllPasswords();
            return ApiResponse.success("密码迁移完成");
        } catch (Exception e) {
            return ApiResponse.error("密码迁移失败: " + e.getMessage());
        }
    }

}
